// 2018-4-4
var xsui = {};

// 2018-4-16
xsui.initButton = function () {
    $('.xsui-btn-edit-dialog').on('click', function () {
        var $btn = $(this);
        var title = $btn.attr('title') ? $btn.attr('title') : $btn.text();
        if (!title) {
            title = '未命名';
        }
        var url = $btn.attr('href');
        var w = $btn.data('dlgwidth') ? $btn.data('dlgwidth') : 800;
        var h = $btn.data('dlgheight') ? $btn.data('dlgheight') : 600;
        layer_show(title, url, w, h);
        return false;
    })
    $('.xsui-datepicker').click(function () {
        WdatePicker();
    })
    $('.xsui-btn-delete-ajax').click(function () {
        var $btn = $(this);
        var confirm_text = '确认要删除吗？';
        var url = $btn.attr('href');
        layer.confirm(confirm_text, function (index) {
            $.ajax({
                type: 'POST',
                url: url,
                dataType: 'json',
                success: function (data) {
                    $btn.parents("tr").remove();
                    layer.msg('已删除!', {icon: 1, time: 1000});
                },
                error: function (data) {
                    console.log(data.msg);
                    alert(data.msg);
                },
            });
        });
    })
    $('.xsui-btn-delete-multi-ajax').click(function () {
        var $btn = $(this);
        var chkboxSelector = $btn.data('checkbox');
        if (!chkboxSelector) {
            layer.msg('未设置表格对象!');
            return false;
        }
        if ($(chkboxSelector).size() < 1) {
            layer.msg('未发现checkbox控件!');
            return false;
        }
        var ids = '';
        $(chkboxSelector + ':checked').each(function () {
            ids += ',' + $(this).val();
        })
        if (ids) {
            ids = ids.substring(1);
        }
        var confirm_text = '确认要删除吗？';
        var url = $btn.attr('href');
        layer.confirm(confirm_text, function (index) {
            $.post(url, {id: ids}, function (data) {
                if (data.status) {
                    $btn.parents("tr").remove();
                    layer.msg('已删除!', {icon: 1, time: 1000});
                } else {
                    layer.msg(data.msg);
                }
            }).error(function (data) {
                console.log(data);
                layer.msg(data.msg);
            });
        });
        return false;
    })
    $('.xsui-btn-set-status-ajax').click(function () {
        var $btn = $(this);
        var confirm_text = '确认要停用吗？';
        var url = $btn.attr('href');
        layer.confirm(confirm_text, function (index) {
            $.get(url, function (data) {
                if (data.status) {
                    if (data.value) {
                        $btn.parents("tr").find(".td-manage").prepend('<a onClick="admin_stop(this,id)" href="javascript:;" title="停用" style="text-decoration:none"><i class="Hui-iconfont">&#xe631;</i></a>');
                        $btn.parents("tr").find(".td-status").html('<span class="label label-success radius">已启用</span>');
                        $btn.remove();
                        layer.msg('已启用!', {icon: 6, time: 1000});
                    } else {
                        $btn.parents("tr").find(".td-manage").prepend('<a onClick="admin_start(this,id)" href="javascript:;" title="启用" style="text-decoration:none"><i class="Hui-iconfont">&#xe615;</i></a>');
                        $btn.parents("tr").find(".td-status").html('<span class="label label-default radius">已禁用</span>');
                        $btn.remove();
                        layer.msg('已停用!', {icon: 5, time: 1000});
                    }
                } else {
                    alert(data.msg);
                }
            })
        });
    })
}
/**
 * 
 * @returns {undefined}
 * @version 2018-4-16
 */
xsui.initDatatables = function (option) {
    var conf = {
        'el': '.table',
        "urlSet": {
            "dataUrl": '',
            "editUrl": '',
            "deleteUrl": '',
        },
        "keySet": {"idField": "id", "textField": "text"},
        'columns': [],
        "createdRow": function () {},
        "columnDefIndex": {"checkboxCol": 0, "editCol": 2, "statusCol": -1, "optionCol": -1},
        "columnDefs": [],
    };
    $.extend(conf, option);
    var $table = $(conf.el);
    if (!conf.urlSet.dataUrl) {
        conf.urlSet.dataUrl = $table.data('srcurl');
    }
    if (!conf.urlSet.editUrl) {
        conf.urlSet.editUrl = $table.data('editurl');
    }
    if (!conf.urlSet.deleteUrl) {
        conf.urlSet.deleteUrl = $table.data('deleteurl');
    }
    if (true) {
        // 多选框列
        if (conf.columnDefIndex.checkboxCol > -1) {
            conf.columnDefs.push({
                "render": function (data, type, row) {
                    return '<input type="checkbox" value="' + data + '" />';
                },
                "targets": conf.columnDefIndex.checkboxCol
            });
        }
        // 快捷编辑列      
        if (conf.columnDefIndex.editCol > -1) {
            conf.columnDefs.push({
                "render": function (data, type, row) {
                    return '<a title="编辑 ' + data + '" href="' + conf.urlSet.editUrl.replace('varid', row[conf.keySet.idField]) + '" class="ml-5 xsui-btn-edit-dialog" style="text-decoration:none">' + data + '</a>';
                },
                "targets": conf.columnDefIndex.editCol
            });
        }
        // 状态开关列      
        if (conf.columnDefIndex.statusCol > -1) {
            conf.columnDefs.push({
                "render": function (data, type, row) {
                    return '<span class="label ' + (data ? 'label-success' : 'label-fail') + ' radius">' + (data ? '已启用' : '已禁用') + '</span>';
                },
                "targets": conf.columnDefIndex.statusCol
            });
        }
        // 操作控制列
        if (conf.columnDefIndex.optionCol > -1) {
            conf.columnDefs.push({
                "render": function (data, type, row) {
                    return '<a title="编辑 ' + row[conf.keySet.textField] + '" href="' + conf.urlSet.editUrl.replace('varid', data) + '" class="ml-5 xsui-btn-edit-dialog" style="text-decoration:none"><i class="Hui-iconfont">&#xe6df;</i></a> <a title="删除 ' + row[conf.keySet.textField] + '" href="' + conf.urlSet.deleteUrl.replace('varid', data) + '" class="ml-5" style="text-decoration:none"><i class="Hui-iconfont">&#xe6e2;</i></a>';
                },
                "targets": conf.columnDefIndex.optionCol
            });
        }
        /* 隐藏第几列 *
         {"visible": false, "targets": [3]} */
    }
    // https://datatables.net/reference/option/
    // http://api.jquery.com/Ajax_Events/
    $table.DataTable({
        "ajax": {
            "url": conf.datasrc,
            "complete": function (data) {
                xsui.initButton();
            },
            "error": function () {
                layer.msg('系统错误, 数据加载失败!');
            }
        },
        "columns": conf.columns,
        searching: false,
        "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "全部"]],
        /* 默认排序 */
        "order": [[1, 'asc']],
        "createdRow": function (row, data, index) {
            /* td单元格加样式类 */
            //$('td', row).eq(7).addClass('td-manage');
            conf.createdRow();
        },
        /* 列渲染 */
        "columnDefs": conf.columnDefs,
    });
}
// 2018-4-4 
xsui.initListPage = function () {
    // https://datatables.net/manual/
    $('.table-sortxx').dataTable({
        "aaSorting": [[1, "desc"]], //默认第几个排序
        "bStateSave": true, //状态保存
        "aoColumnDefs": [
            //{"bVisible": false, "aTargets": [ 3 ]} //控制列的隐藏显示
            {"orderable": false, "aTargets": [0, 1]}// 指定列不参与排序
        ]
    });
    xsui.initButton();
}
// 2018-4-4
xsui.initEditDialogPage = function () {
    $(function () {
        $('.skin-minimal input').iCheck({
            checkboxClass: 'icheckbox-blue',
            radioClass: 'iradio-blue',
            increaseArea: '20%'
        });

        $("#form-admin-add2").validate({
            rules: {
                adminName: {
                    required: true,
                    minlength: 4,
                    maxlength: 16
                },
                password: {
                    required: true,
                },
                password2: {
                    required: true,
                    equalTo: "#password"
                },
                sex: {
                    required: true,
                },
                phone: {
                    required: true,
                    isPhone: true,
                },
                email: {
                    required: true,
                    email: true,
                },
                adminRole: {
                    required: true,
                },
            },
            onkeyup: false,
            focusCleanup: true,
            success: "valid",
            submitHandler: function (form) {
                $(form).ajaxSubmit({
                    type: 'post',
                    url: "xxxxxxx",
                    success: function (data) {
                        layer.msg('添加成功!', {icon: 1, time: 1000});
                    },
                    error: function (XmlHttpRequest, textStatus, errorThrown) {
                        layer.msg('error!', {icon: 1, time: 1000});
                    }
                });
                var index = parent.layer.getFrameIndex(window.name);
                parent.$('.btn-refresh').click();
                parent.layer.close(index);
            }
        });
    });
}